--[[
-- Author:      feilong
-- DateTime:    2020-10-10 17:19:33
-- Description: 节点的服务管理
    1更方便的取得节点中各服务的信息，
    2处理节点间的消息
    3开启Gate端口监听消息，client消息由watchdog处理
--]]


local skynet = require "skynet"


local MessageHandler = class("MessageHandler")

---------------------------------------------------------
-- Private
---------------------------------------------------------
function MessageHandler:ctor()
	self.services = {}
    self.server_config = dofile(skynet.getenv("server_config"))
	self:register()	
end

--注册本服务里的消息
function MessageHandler:register()    
    g.Log():debug("i am manager register!")
    self.message_dispatch = g.MsgDis()
    self.message_dispatch:register('start', handler(self, self.start))
    self.message_dispatch:register('cluster_broadcast', handler(self, self.clusterBroadcast)) --给所有集群节点发消息  
    self.message_dispatch:register('cluster_broadcast_res', handler(self, self.clusterBroadcastRes)) --收到集群广播

    self.message_dispatch:register('get_server', handler(self, self.getServer)) --取得指定类型的服务器节点
    self.message_dispatch:register('send_to_user', handler(self, self.sendToUser)) --
end


---------------------------------------------------------
-- CMD
---------------------------------------------------------
function MessageHandler:start()
    g.Log():debug("manger start")

    --加载了的服务列表
    g.Message():callService(".launcher", "LIST")
    g.Log():debug("list--> ", list, skynet.self())
    
    local watchdog = skynet.queryservice("watchdog/watchdog_service") --如果没起动会阻塞
    local node_info = self.server_config.node_info
    local gate = skynet.newservice("gate")
    local conf = {
        port = node_info.client_port,
        maxclient = maxclient,
        nodelay = true,        
        watchdog = watchdog
    }
    skynet.name(".gate", gate)
    g.Message():callService(gate, "open",conf)

    g.Log():debug("open gate--> ", node_info.client_port)


    -- g.cluster_manager:broadcast("test")
end


function MessageHandler:clusterBroadcast(msg, msg_name)
    g.Log():debug("manger clusterBroadcastReq")
    if not msg_name then 
        msg_name = "cluster_broadcast_res"
    end
    g.cluster_manager:broadcast(msg_name, msg)
    return true
end

function MessageHandler:clusterBroadcastRes(from_server, msg)
    g.Log():debug("manger clusterBroadcastRes")
    return true
end

function MessageHandler:getServer(server_type, uid)
    -- body
    local node = g.cluster_manager:getNodeByTypeUid(server_type, uid)
    return node
end

function MessageHandler:sendToUser(session, msg_name, msg_data, ...)
    g.Message():sendService(".watchdog", "send_to_user", session, msg_name, msg_data, ...)
end


return MessageHandler